package nsn.message.aggregator.commands;


import nsn.message.aggregator.model.behaviour.Updatable;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.handlers.HandlerUtil;

/**
 * 
 * 
 * @author Lukasz Nowak
 * @since 10-03-2011
 * 
 */
public class UpdateHandler extends AbstractHandler {

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		final IWorkbenchSite site = HandlerUtil.getActiveSite(event);
		final IWorkbenchPage page = site.getPage();
		final ISelection selection = page.getSelection();

		if (selection instanceof IStructuredSelection) {
			final Object selectedObj = ((IStructuredSelection) selection)
					.getFirstElement();

			if (selectedObj instanceof Updatable) {
				final Job job = new Job("Updating ...") {

					@Override
					protected IStatus run(IProgressMonitor monitor) {
						monitor.setTaskName(getName());
						((Updatable) selectedObj).update();
						monitor.done();
						return Status.OK_STATUS;
					}
				};
				job.schedule();

			}
		}
		return null;
	}

}
